#!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
  DOCKER_IP=127.0.0.1
else
  echo "Docker environment not detected."
  exit 1
fi
set -e

if test -z "$COMPOSE_PROJECT_NAME"
then
  CWD=${PWD##*/}
  export COMPOSE_PROJECT_NAME=${CWD/_/}
fi

mkdir -p build

get_exposed_port() {
  docker-compose port $1 $2 | cut -d: -f2
}

docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate

PORT=$(get_exposed_port postgres 5432)

printf "Waiting for postgres "
export PG
until docker-compose exec postgres pg_isready -q; do
  printf "."
  sleep 1
done
echo " done"

cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
